package com.financing.wap.web.controller.api;


import java.io.File;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.financing.sms.service.MessageService;
import com.financing.wap.dao.wherecondition.WC;
import com.financing.wap.dao.wherecondition.WhereCondition;
import com.financing.wap.dto.*;
import com.financing.wap.service.*;
import com.financing.wap.service.impl.SmsServiceImpl;
import com.financing.wap.service.impl.UserInfoServiceImpl;
import com.financing.wap.util.*;
import com.financing.wap.vo.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.activities.ActivitiesBusinessObject;
import com.financing.wap.activities.impl.ActivitiesYLYXHDImpl;
import com.financing.wap.common.BizEnums;
import com.financing.wap.common.BizEnums.DeptType;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.BizEnums.CommonEnums;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.common.SqlName.FaUserSql;
import com.financing.wap.web.controller.BaseController;

/**
 * 个人信息API
 * @author jtl
 *
 */
@Controller("apiUserController")
@RequestMapping("/api/user")
public class UserController extends BaseController {
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IUserService userService;

	@Autowired
	private ISmsService smsService;

	@Autowired
	public ISmsNewService smsNewService;

	@Autowired
	private IClientService clientService;

	@Autowired
	private IOrderService orderService;

	@Autowired
	private ICheckCodeService checkCodeServiceImpl;

	@Autowired
	private IActivitieGiftService activitieGiftServiceImpl;

	@Autowired
	private IProjectLikeService projectLikeServiceImpl;

	@Autowired
	private IAuthenticationService authenticationService;
	@Autowired
	private IActivitiesWinListService activitiesWinListServiceImpl;

	@Autowired
	private IActivitesService activitesServiceImpl;

	@Autowired
	private ICorpService corpService;

	@Autowired
	private IWechatCoreService wechatCoreServiceImpl;

	@Autowired
	private IBankCardService bankCardServiceImpl;

	@Autowired
	private IFpFaUserSaysayCommentService fpFaUserSaysayCommentService;

	@Autowired
	private IPaymentService paymentServiceImpl;// 支付流水服务

	private String fileBaseDir = PropertiesUtils.getValue("fileBaseDir");

	@Autowired
	private IFpFaUserSaysayService fpFaUserSaysayService;

	@Autowired
	private IFpShopperProductService fpShopperProductService; //店铺服务

	@Autowired
	private IShopperUserInfoService shopperUserInfoService;

	@Autowired
	private IFpFaUserDataService userDataService;

	@Autowired
	private ISystemService isystemService;

	@Autowired
	private IFpShopProjectInformationService fpShopProjectInformationService;

	@Autowired
	public MessageService messageServiceImpl;

	@Autowired
	public UserInfoServiceImpl userInfoServiceImpl;

	@RequestMapping("view")
	@ResponseBody
	public ResultMap view(HttpServletRequest request, HttpServletResponse response){

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String faId = loginUser.getId();


		ResultMap result = new ResultMap();
		try {
			UserDTO user = userService.queryUserById(faId);
			//查询是否活动中 
			String start= "2016-01-01 00:00:00";
			String end = "2017-10-24 23:59:59";
			//判断时间
			Date inputDate = new Date();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = sf.parse(start);
			Date d2 = sf.parse(end);
			//在设定时间内
			if(inputDate.before(d2) && inputDate.after(d1) && (user.getRole()==null || !user.getRole().equals("2"))){
				//修改状态为通过
				UserDTO ud = new UserDTO();
				ud.setId(user.getId());
				ud.setuShoprole("2"); //
				ud.setFpTempRole("1"); //活动通过标识
				loginUser.setRole("2");
				ud.setLoginName(user.getLoginName());
				userService.updateUser(ud);
			}

			//判断shop添加关联信息 进行添加
			if(!StringUtils.isBlank(loginUser.getLoginName())){
				FpFaUserDataDTO fpFaUserData = new FpFaUserDataDTO();
				fpFaUserData.setLoginName(loginUser.getLoginName());
				List<FpFaUserDataDTO> ud=userDataService.queryList(fpFaUserData);

				if(ud.size()==0){
					DTOdateSetUtil.setCreateInfo(fpFaUserData);
					fpFaUserData.setDeleteTag(CommonEnums.DELETE_FLAG_1);
					userDataService.insert(fpFaUserData);
				}
			}


			FaUserDTO faUser = userService.getUserById(faId);

			//屏蔽 身份证号码
			if(StringUtils.isNotBlank(faUser.getuNumber()) && faUser.getuNumber().length() == 18){
				String a =  faUser.getuNumber();
				faUser.setuNumber(a.substring(0, 4)+"****"+a.substring(a.length()-4, a.length()));
			}

			//选择最优的图片  （上传 > 微信 >默认）
			String reg = "/upload/faUser/image/\\d+.png";
			if(StringUtils.isBlank(faUser.getuImage()) || faUser.getuImage().matches(reg)){
				if(faUser.getFaUserWechatDTO() != null && StringUtils.isNotBlank(faUser.getFaUserWechatDTO().getHeadimgurl())){
					faUser.setuImage(faUser.getFaUserWechatDTO().getHeadimgurl());
				}
			}

			logger.info("flagVistProjectInfo user view start");
			boolean flagVistProjectInfo=false;
			try {
				java.sql.Date sqlDate = DateUtil.getSqlDate(CommonConstantUtil.DATE_SIMU);
				java.sql.Date createDate = DateUtil.toSqlDate(faUser.getCreateDate());
				if(createDate.before(sqlDate)){//今天注册前   都能访问
					flagVistProjectInfo=true;
				}else{
					//注册之后的  需要是否认证通过
					String role=faUser.getuRole();
					boolean b = StringUtils.isNotBlank(role)
							&&!role.equals("1")
							&&!role.equals("98")
							&&!role.equals("99");
					if(b){
						flagVistProjectInfo=true;
					}
				}
			} catch (Exception e) {
				log.error("get flagVistProjectInfo error",e);
			}
			logger.info("flagVistProjectInfo user view end:"+flagVistProjectInfo);
			faUser.setFlagVistProjectInfo(flagVistProjectInfo);

			result.setAttribute("user", faUser);

			String token = faUser.getId();
			token = SecureUtil.encrypt(token).replaceAll("=", "");
			logger.info("===========================viewtoken:"+token);
			result.setAttribute("token", token);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("==>warn messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	@RequestMapping(value="/edit")
	@ResponseBody
	public ResultMap editPost(HttpServletRequest request, HttpServletResponse response,FaUserDTO faUser){
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String faId = loginUser.getId();
		faUser.setUpdateBy(faId.toString());
		ResultMap result = new ResultMap();
		try {
			FaUserDTO  fu = new FaUserDTO();
			fu.setId(faId);
			fu.setuRole("98");
			userService.updateFaUserInfo(fu);

			UserDTO user = userService.queryUserLoginName(loginUser);
			if(user==null){
				logger.info("edit action erro:");
				result.setStatus(STATUS.NEED_LOGIN);
				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
			}
			session.setUser(user);
			//sfa认证
			//			AuthenticationDTO attd = authenticationService.queryAuthInfo(faId);
			//			if(attd == null){
			//				attd = new AuthenticationDTO();
			//			}
			//			attd.setTrade(StringUtil.isNullOrEmptyStr(request.getParameter("trade"))==true?attd.getTrade():request.getParameter("trade"));
			//			attd.setFaId(faId);
			//			if(!StringUtil.isNullOrEmptyStr(request.getParameter("tradeAge"))){
			//				try{
			//					attd.setTradeAge(Integer.valueOf(request.getParameter("tradeAge")));
			//				}catch(Exception e){
			//					attd.setTradeAge(0);
			//				}
			//			}
			//			authenticationService.updateAuthInfo(attd);
			//shop认证
			FpFaUserDataDTO fud = new FpFaUserDataDTO();
			fud.setLoginName(user.getLoginName());
			List<FpFaUserDataDTO> fuds =  userDataService.queryList(fud);
			if(fuds.size()!=1){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_2024);
				return result;
			}
			fud= fuds.get(0);

			fud.setUJob(faUser.getuJob());
			fud.setUSex(faUser.getuSex()+"");
			fud.setURealName(faUser.getuRealName());
			fud.setUCardType(faUser.getuCardType()+"");
			fud.setUCompany(faUser.getuCompany());
			fud.setuCardAddress(faUser.getuCardAddress());
			//			提交认证时间
			fud.setAddAuthDate(DateUtil.getString(new Date(), "yyyy-MM-dd HH:mm:ss"));
			userDataService.update(fud);


			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.warn("==>warn messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}


	@RequestMapping(value="/changepwd",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap changepwd(HttpServletRequest request, HttpServletResponse response,RegisterDTO register){
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		ResultMap result = new ResultMap();

		//非机构账户不传moblie
		if((register.getMobile() == null)){
			String securePassword = SecureUtil.MD5EncryptAndBase64(register.getPassword());
			UserDTO user = new UserDTO();
			user.setLoginName(loginUser.getLoginName());
			user.setPassword(securePassword);

			user = userService.getUserByUF(user);
			if(user == null){
				log.info("error password!");
				result.setStatus(ResultMap.STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_USER_PASSWORD_ERROR);
				result.setMessage("旧密码校验失败");
				return result;
			}
		}

		//校验验证码
		if(checkCodeServiceImpl.CheckCodeSwitch()){
			ResultMap resultOtp = checkOtpCode(loginUser.getMobile(),register.getvCode());

			if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
				result.setStatus(resultOtp.getStatus());
				result.setStatusCode(resultOtp.getStatusCode());
				result.setMessage(resultOtp.getMessage());
				return result;
			}
		}

		FaUserDTO faUser = new FaUserDTO();
		//当前登录人ID
		String faId = loginUser.getId();
		faUser.setUpdateBy(faId.toString());
		faUser.setuPassWord(SecureUtil.MD5EncryptAndBase64(register.getConfirmPassword()));
		if(register.getMobile() != null){
			faUser.setuLoginName(register.getMobile());
			faUser.setuManagerId(faId);
			if(null==register.getId()){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			faUser.setId(register.getId());
		}else{
			faUser.setuLoginName(loginUser.getLoginName());
			faUser.setId(faId);
		}

		try {
			userService.updateFaUserInfo(faUser);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.warn("==>warn messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	@RequestMapping(value="/changepwdForget")
	@ResponseBody
	public ResultMap changepwdForget(HttpServletRequest request, HttpServletResponse response,RegisterDTO register){

		ResultMap result = new ResultMap();
		log.info("In  changepwdForget Begin!");
		//参数为空判断
		if(StringUtil.isNullOrEmptyStr(register.getMobile()) || StringUtil.isNullOrEmptyStr(register.getvCode()) || StringUtil.isNullOrEmptyStr(register.getConfirmPassword())){
			log.info("In  changepwdForget Parameter  null!");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}
		//校验验证码
		if(checkCodeServiceImpl.CheckCodeSwitch()){
			ResultMap resultOtp = checkOtpCode(register.getMobile(),register.getvCode());
			if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
				result.setStatus(resultOtp.getStatus());
				result.setStatusCode(resultOtp.getStatusCode());
				result.setMessage(resultOtp.getMessage());
				return result;
			}
		}

		//根据手机号查询用户信息
		UserDTO user = new UserDTO();
		user.setLoginName(register.getMobile());
		UserDTO userBean = userService.queryUserByMobile(user);
		if(userBean == null){
			log.info("In changepwdForget userByMobile  undefined  ");
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_MOBILE_NUMBER_UNDEFINED);
			result.setMessage("手机号在本系统中不存在！");
			return result;
		}
		log.info("In  changepwdForget updateFaUserInfo!");
		//修改用户密码
		FaUserDTO faUser = new FaUserDTO();
		faUser.setUpdateBy(userBean.getId().toString());
		faUser.setuPassWord(SecureUtil.MD5EncryptAndBase64(register.getConfirmPassword()));
		faUser.setuLoginName(userBean.getLoginName());
		faUser.setId(userBean.getId());
		try {
			userService.updateFaUserInfo(faUser);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			log.info("In  changepwdForget updateFaUserInfo SUCCESS!");
		}catch(Exception e) {
			logger.error("In  changepwdForget updateFaUserInfo error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		log.info("In  changepwdForget end!");
		return result;
	}
	@RequestMapping(value="/checkotp")
	@ResponseBody
	public ResultMap checkpwd(HttpServletRequest request, HttpServletResponse response,RegisterDTO register){

		ResultMap result = new ResultMap();
		log.info("In  checkotp Begin!");
		//参数为空判断
		if(StringUtil.isNullOrEmptyStr(register.getMobile()) || StringUtil.isNullOrEmptyStr(register.getvCode()) ){
			log.info("In  changepwdForget Parameter  null!");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}
		//校验验证码
		if(checkCodeServiceImpl.CheckCodeSwitch()){

			ResultMap resultOtp = checkOtpCode(register.getMobile(),register.getvCode());
			if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
				result.setStatus(resultOtp.getStatus());
				result.setStatusCode(resultOtp.getStatusCode());
				result.setMessage(resultOtp.getMessage());
				return result;
			}
		}
		//根据手机号查询用户信息
		UserDTO user = new UserDTO();
		user.setLoginName(register.getMobile());
		UserDTO userBean = userService.queryUserByMobile(user);
		if(userBean == null){
			log.info("In checkotp userByMobile  undefined  ");
			result.setStatus(ResultMap.STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_MOBILE_NUMBER_UNDEFINED);
			result.setMessage("手机号在本系统中不存在！");
			return result;
		}
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

		log.info("In  checkotp end!");
		return result;
	}
	@RequestMapping(value="/registerCount",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap registerCount(HttpServletRequest request, HttpServletResponse response,FaUserDTO faUser){
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		//当前登录人ID
		String faId = loginUser.getId();
		faUser.setUpdateBy(faId.toString());
		ResultMap result = new ResultMap();
		try {
			Integer count = userService.queryCountBySourceCode(faId);
			result.setAttribute("registerCount", count);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.warn("==>warn messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	@RequestMapping(value="/allInfoCount",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap allInfoCount(HttpServletRequest request, HttpServletResponse response,FaUserDTO faUser){
		Session session = SessionUtil.getSession();
		ResultMap result = new ResultMap();
		try{
			UserDTO loginUser = session.getUser();
			//当前登录人ID
			String faId = loginUser.getId();

			//红包
			if(request.getParameter("giftCount") != null){
				result.setAttribute("giftCount",activitieGiftServiceImpl.countActivitiesGift(faId));
			}

			//收藏
			if(request.getParameter("productLikeCount") != null){
				ProjectLikeDTO projectLikeDTO = new ProjectLikeDTO();
				projectLikeDTO.setuId(faId);
				projectLikeDTO.setLikeType(new Integer(1));
				result.setAttribute("productLikeCount", projectLikeServiceImpl.countProjectLikeForFa(projectLikeDTO));
			}

			//客户
			if(request.getParameter("clientUserCount")!=null){
				QueryClientUserVo  qcuv = new QueryClientUserVo();
				qcuv.setFaId(faId);
				qcuv.setcLevel(0);
				result.setAttribute("clientUserCount", clientService.getClientUserListCount(qcuv));
			}

			//成交
			if(request.getParameter("orderDealCount")!=null){
				result.setAttribute("orderDealCount", orderService.countDealOrder(faId));
			}

			//返佣
			if(request.getParameter("orderCommissionCount")!=null){
				result.setAttribute("orderCommissionCount", MoneyUtil.conversion(orderService.orderCommissionCount(faId),2));
			}

			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
		}catch(Exception e){
			log.error("query activity gift count error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}

	/**
	 * 名片编辑
	 * @param request
	 * @param response
	 * @param uRealName
	 * @param uCardAddress
	 * @return
	 */
	@RequestMapping(value="/cardedit")
	@ResponseBody
	public ResultMap cardeditPost(HttpServletRequest request, HttpServletResponse response,String uRealName,String uCardAddress,String sourceCode, String imgServerId,String authSource){

		log.info("In the cardeditPost begin!");
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		FaUserDTO faUser  = new FaUserDTO();
		//当前登录人ID
		String faId = loginUser.getId();
		faUser.setUpdateBy(faId.toString());
		ResultMap result = new ResultMap();

		try {
			faUser.setId(faId);
			//不为空表示是微信提交认证，传过来是媒体id，根据id从微信服务器下载到本服务器
			if(!StringUtils.isBlank(imgServerId)){
				StringBuffer fileFullPath = new StringBuffer();
				fileFullPath.append(fileBaseDir)
				.append("/upload/faUser/cert")
				.append("/")
				.append(DateUtil.getDate())
				.append("/");

				//判断目录存在否
				File dir = new File(fileFullPath.toString());
				if(!dir.exists()){
					dir.mkdirs();
				}
				//生成文件
				fileFullPath.append(System.currentTimeMillis())
				.append(imgServerId)
				.append(".jpg");

				//是否成功
				if(wechatCoreServiceImpl.getFilePath(imgServerId, fileFullPath.toString())){
					uCardAddress = fileFullPath.toString().substring(fileBaseDir.length());
				}else{
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
					return result;
				}
				//微信媒体id 默认是 YLYXHD活动
				if(StringUtils.isBlank(authSource)){
					authSource = ActivitiesYLYXHDImpl.activitiesCode;
				}
			}

			//如果authSource 空默认PT
			if(StringUtils.isBlank(authSource)){
				authSource = Constants.MEDIA_SOURCE_PT;
			}

			//参数为空判断     不需要 判断 真实姓名
			if(StringUtil.isNullOrEmptyStr(uCardAddress) ){
				log.info("In the cardeditPost Parameter  null!");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			log.info("In the cardeditPost Parameter !"+faId);
			UserDTO userDtoView = userService.queryUserById(faId);
			log.info("In the cardeditPost Parameter !"+userDtoView.getRole());
			if(!Constants.USER_ROLE_NO_AUDIT.equals(userDtoView.getRole()) && !Constants.USER_ROLE_AUDIT_FAILURE.equals(userDtoView.getRole())){
				log.info("In the cardeditPost user role no is 1 or 99!");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
				return result;
			}
			faUser.setuRealName(uRealName);
			faUser.setuCardAddress(uCardAddress);
			faUser.setuRole(Constants.USER_ROLE_AUDIT);
			faUser.setAuthSource(authSource);
			userService.updateFaUserInfo(faUser);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			log.info("In the cardeditPost end!");

			//注入活动
			try {
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("userId", faId);
				map.put("shareUserId", sourceCode);
				activitesServiceImpl.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_FaUser_Submit_Auth, map);
			} catch (Exception e) {
				log.error("ylyxhdSend ActivitiesJobExecutionObejct error", e);
			}

			//如果为cd500  发送短信 
			if(ActivitiesYLYXHDImpl.activitiesCode.equals(authSource)){
				boolean smsSwitch = smsNewService.smsSwitch("uploadCardSendSms");
				if(smsSwitch){
					try {
						Map<String,Object> msmParam = new HashMap<String,Object>();
						String msg = (String) MessageUtil.getMessage("messageAndMail","activityAddCard", msmParam).get(MessageUtil.KEY_CONTENT);
						String loginName = loginUser.getLoginName();
						messageServiceImpl.sendSMSForSFA(loginName,msg);
						log.info("mailSenderService cardedit sendSMS end");
					} catch (Exception e) {
						log.error("cardedit sendSMS",e);
					}
				}
			}
		}catch(Exception e) {
			logger.error("cardeditPost error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 邀请理财师列表
	 * @param request
	 * @param response
	 * @param uRealName
	 * @param uCardAddress
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/inviteFaList")
	@ResponseBody
	public ResultMap inviteFaList(HttpServletRequest request, HttpServletResponse response,Pager pager){

		log.info("In the inviteFaList begin!");
		ResultMap result = new ResultMap();
		try{
			Map<String, Object> queryParams = new HashMap<String, Object>();
			UserDTO user = getSession(true).getUser();
			queryParams.put("pager", pager);
			queryParams.put("user",user);

			int count = userService.getInviteFaListByUserIdCount(user);
			pager.setTotalCount(count);

			List<UserDTO> list;
			if(count>0){
				list = userService.getInviteFaListByUserId(queryParams);

				//登录名称加密
				for (UserDTO bean:list) {
					if (bean == null) {
						continue;
					}
					bean.setLoginName(StringUtil.encryptCardNumber(bean
							.getLoginName()));

				}
			}else{
				list = Collections.EMPTY_LIST;
			}

			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", list);
			result.setAttribute("pager", pager);

			log.info("In ProductCompanyController productlist end!");
			return result;
		}catch(Exception e){
			log.error("error ProductCompanyController productlist:",e);
			result.setStatus(ResultMap.STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
	}
	/**用户唯一识别码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("uuid")
	@ResponseBody
	public ResultMap uuid(HttpServletRequest request, HttpServletResponse response){

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		ResultMap result = new ResultMap();
		try {
			String  uuid =SecureUtil.encrypt( loginUser.getId()+Constants.UUID_DELIMITER+loginUser.getLoginName());
			result.setAttribute("uuid", uuid);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("get user uuid error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**用户唯一识别码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getUserForUuid")
	@ResponseBody
	public ResultMap getUserForUuid(HttpServletRequest request, HttpServletResponse response,String uuid){

		ResultMap result = new ResultMap();
		try {
			log.info("In  getUserForUuid Begin!");
			//参数为空判断
			if(StringUtil.isNullOrEmptyStr(uuid) ){
				log.info("In  getUserForUuid Parameter  null!");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			//初始化查询参数
			String  userinfo =SecureUtil.decrypt(uuid);
			String[]  userinfos = userinfo.split(Constants.UUID_DELIMITER);
			UserDTO user = new UserDTO();
			user.setId(userinfos[0]);
			user.setLoginName(userinfos[1]);
			Map<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("user", user);

			//查询信息
			Map<String, Object> resMap = userService.getUser(queryParams);
			for (String key : resMap.keySet()) {
				if(resMap.get(key) == null){
					resMap.put(key, "");
				}
			}
			result.setAttribute("dto", resMap);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			log.info("In  getUserForUuid end!");
		}catch(Exception e) {
			logger.error("get user uuid error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 获取用户中奖记录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getWinList")
	@ResponseBody
	public ResultMap getWinList(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		try {
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			log.info("In getWinList begin!");

			//查询活动时间
			ActivitesDTO activitesDTO = activitesServiceImpl.searchActivitesByCode("BWCSY");
			//获取用户中奖列表
			Map<String, Object> queryParams = new HashMap<String, Object>();
			ActivitiesWinListDTO activitiesWinListDTO = new ActivitiesWinListDTO();
			queryParams.put("activitiesWinListDTO", activitiesWinListDTO);
			queryParams.put("createDateStar",activitesDTO.getActiviesStartTime());
			activitiesWinListDTO.setActiviesCode("BWCSY");
			activitiesWinListDTO.setUserId(loginUser.getId());
			List<ActivitiesWinListVo> list = activitiesWinListServiceImpl.getActivitiesWinListList(queryParams);

			queryParams.put("createDateStar",activitesDTO.getActiviesStartTime());
			queryParams.put("createDateEnd",activitesDTO.getActiviesEndTime());
			queryParams.put("userId", loginUser.getId());
			queryParams.put("activitiescode", "BWCSY");

			//获取用户在活动期间订单总金额
			BigDecimal sum = orderService.getOrderAmountCount(queryParams);

			result.setAttribute("list", list);
			result.setAttribute("sum", sum);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			log.info("In  getWinList end!");
		}catch(Exception e) {
			logger.error("get getWinList error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 获取理财师列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public ResultMap sfaList(HttpServletRequest request, HttpServletResponse response,Pager pager,FaUserVO userVo){

		ResultMap result = new ResultMap();
		try {
			log.info("In  sfaList begin!");

			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			//判断是否是机构用户
			if(!Constants.FA_TYPE_CORP.equals(loginUser.getuType()) && !Constants.FA_TYPE_CORP_FA.equals(loginUser.getuType()) ){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setMessage("违法操作");
				return result;
			}
			userVo.setId(loginUser.getId());
			userVo.setuType(loginUser.getuType());


			Map<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("pager", pager);
			queryParams.put("user", userVo);
			Integer count = userService.getSFAListCount(queryParams);
			pager.setTotalCount(count);

			List<Map<String, Object>> list= userService.getSFAList(queryParams);


			//对id 生成 uuid
			for (Map<String, Object> map:list) {
				String uuid =SecureUtil.encrypt( map.get("id")+Constants.UUID_DELIMITER+map.get("uLoginName"));
				map.put("uuid", uuid);
				//去除 uLoginName 属性
				map.put("uLoginName", "");

				//获取机构子账号的理财数
				Map<String, Object> queryMap = new HashMap<String, Object>();
				FaUserVO userBean = new FaUserVO();
				userBean.setId(map.get("id").toString());
				userBean.setuType(Constants.FA_TYPE_CORP_FA);
				queryMap.put("user", userBean);
				Integer sfaCount = userService.getSFAListCount(queryMap);
				map.put("sfaCount", sfaCount);

				//如果为null 赋值 为""
				for (String key : map.keySet()) {
					if(map.get(key) == null){
						map.put(key, "");
					}
				}
			}
			result.setAttribute("list", list);
			result.setAttribute("pager", pager);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			log.info("In  sfaList end!");
		}catch(Exception e) {
			logger.error("get sfaList error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 获取理财师列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("sonList")
	@ResponseBody
	public ResultMap sonList(HttpServletRequest request, HttpServletResponse response,Pager pager,FaUserVO userVo){

		ResultMap result = new ResultMap();
		try {
			log.info("In  sfaList begin!");

			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			//判断是否是机构用户
			if(!Constants.FA_TYPE_CORP.equals(loginUser.getuType())	){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setMessage("违法操作");
				return result;
			}

			//子机构id
			//初始化查询参数
			String  userinfo =SecureUtil.decrypt(userVo.getUuid());
			String[]  userinfos = userinfo.split(Constants.UUID_DELIMITER);
			UserDTO user = new UserDTO();
			user.setId(userinfos[0]);
			userVo.setId(user.getId());
			userVo.setuType(Constants.FA_TYPE_CORP_FA);


			//查询下属理财师
			Map<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("pager", pager);
			queryParams.put("user", userVo);
			Integer count = userService.getSFAListCount(queryParams);
			pager.setTotalCount(count);

			List<Map<String, Object>> list= userService.getSFAList(queryParams);


			//对id 生成 uuid
			for (Map<String, Object> map:list) {
				String uuid =SecureUtil.encrypt( map.get("id")+Constants.UUID_DELIMITER+map.get("uLoginName"));
				map.put("uuid", uuid);
				//去除 uLoginName 属性
				map.put("uLoginName", "");

				//如果为null 赋值 为""
				for (String key : map.keySet()) {
					if(map.get(key) == null){
						map.put(key, "");
					}
				}
			}
			result.setAttribute("list", list);
			result.setAttribute("pager", pager);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			log.info("In  sfaList end!");
		}catch(Exception e) {
			logger.error("get sfaList error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	@RequestMapping("invitationCode")
	@ResponseBody
	public ResultMap invitationCode(){
		ResultMap result = new ResultMap();
		try {
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			CompanyInvitationCodeDTO cic = new CompanyInvitationCodeDTO();
			cic.setCompanyId(loginUser.getId());
			result.setAttribute("cic", corpService.getInvitationCode(cic));
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("get invitationCode error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 新增用户交易密码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/addTradePwd")
	@ResponseBody
	public synchronized ResultMap addTradePwd(HttpServletRequest request, HttpServletResponse response){


		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("addTradePwd request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();



			String tradePwd =  request.getParameter("tradePwd");//交易密码
			//检查参数是否有空值
			if(BasicUtils.isEmpty(tradePwd) || userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			//4，检查用户状态
			// 检查用户是否已经存在绑定银行卡（目前只允许绑定一张）
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
				return result;
			}

			//不能与登陆密码一样
			if( userInfo.getPassword().equals( SecureUtil.MD5EncryptAndBase64(tradePwd))){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4006);
				result.setMessage("不能与登陆密码一样");
				return result;
			}

			//密码长度检查
			if( 6 > tradePwd.length() ||  tradePwd.length() > 20 ){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_TYPE_ERROR);
				result.setMessage("交易密码长度只能6-20位");
				return result;
			}

			if( logger.isInfoEnabled() ){
				logger.info("addTradePwd request userService!");
			}

			userInfo.setTradePwd(SecureUtil.MD5EncryptAndBase64(tradePwd));
			userInfo.setTradeErrTimes(0L);
			userService.updateUser(userInfo);

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			if( logger.isInfoEnabled() ){
				logger.info("addTradePwd request end!");
			}

		} catch (Exception e) {
			logger.error("addTradePwd error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 检查用户是否已存在交易密码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/isExistTradePwdBindingCard")
	@ResponseBody
	public synchronized ResultMap isExistTradePwdBindingCard(HttpServletRequest request, HttpServletResponse response){


		ResultMap result = new ResultMap();
		if( logger.isInfoEnabled() ){
			logger.info("isExistTradePwdBindingCard request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();



			//检查参数是否有空值
			if( userId== null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			//4，检查用户状态
			// 检查用户是否已经存在绑定银行卡（目前只允许绑定一张）
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
				return result;
			}

			//查看用户是否绑定卡了
			if(StringUtils.isEmpty(userInfo.getRealPaperNo())){
				result.setAttribute("bindingCard", "0");
			}else{
				result.setAttribute("bindingCard", "1");
			}

			//查看用户是否设置交易密码
			if(StringUtils.isEmpty(userInfo.getTradePwd())){
				result.setAttribute("tradePwd", "0");
			}else{
				result.setAttribute("tradePwd", "1");
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			if( logger.isInfoEnabled() ){
				logger.info("isExistTradePwdBindingCard request end!");
			}
		} catch (Exception e) {
			logger.error("isExistTradePwdBindingCard error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}


	/**
	 * 修改用户交易密码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/changTradePwd")
	@ResponseBody
	public synchronized ResultMap changTradePwd(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		if( logger.isInfoEnabled() ){
			logger.info("changTradePwd request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();



			String tradePwd =  request.getParameter("tradePwd");//新的交易密码
			String loginPwd =  request.getParameter("loginPwd");//旧登陆密码
			String oldTradePwd =  request.getParameter("oldTradePwd");//旧的交易密码


			//检查数据是否为空
			if(BasicUtils.isEmpty(loginPwd, oldTradePwd, tradePwd)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			// 1，检查用户是否存在
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
				return result;
			}

			//2，新旧密码不能一致
			if( tradePwd.equals(oldTradePwd)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4009);
				result.setMessage("新旧密码不能一致");
				return result;
			}
			//3，密码长度检查
			if( 6 > tradePwd.length() ||  tradePwd.length() > 20 ){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_TYPE_ERROR);
				result.setMessage("交易密码长度只能6-20位");
				return result;
			}

			//登陆密码是否匹配
			if(userInfo.getPassword().equals(SecureUtil.MD5EncryptAndBase64(loginPwd))){
				//不能与登陆密码一样.该检查必须放置在登陆密码检查之后。如果顺序反向，则意味着用户可以尝试出用户的登陆密码
				if( userInfo.getPassword() .equals(SecureUtil.MD5EncryptAndBase64(tradePwd)) ){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_4006);
					result.setMessage("不能与登陆密码一样");
					return result;
				}else{
					if(SecureUtil.MD5EncryptAndBase64(oldTradePwd).equals(userInfo.getTradePwd())){//旧交易密码是否匹配
						userInfo.setTradePwd(SecureUtil.MD5EncryptAndBase64(oldTradePwd));
						userInfo.setTradeErrTimes(0l);
						userService.updateUser(userInfo);

						result.setStatus(STATUS.SUCCESS);
						result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
					}else{
						result.setStatus(STATUS.FAILE);
						result.setStatusCode(ResultMap.STATUS_CODE_4010);
					}
				}
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PWS_ERROR);
				result.setMessage("帐户名密码错误");
				return result;
			}
			if( logger.isInfoEnabled() ){
				logger.info("changTradePwd request end!");
			}
		} catch (Exception e) {
			logger.error("changTradePwd error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 查看用户银行卡信息
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/queryBingdingCard")
	@ResponseBody
	public ResultMap queryBingdingCard(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		if( logger.isInfoEnabled() ){
			logger.info("queryBingdingCard request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}

			String cardId =  request.getParameter("cardId");//旧的交易密码

			String userId = loginUser.getId();

			Map<String,Object> map = new HashMap<String,Object>();

			map.put("userId", userId);
			if(!BasicUtils.isEmpty(cardId)){
				map.put("cardId", cardId);
			}
			map.put("payPlat", BizEnums.PayEnums.PAY_3PLAT_BAOFOO);

			List<BingdingCardVO>  list = bankCardServiceImpl.queryUserBindedcardList(map);

			list = convertCardList(list);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", list);
			if( logger.isInfoEnabled() ){
				logger.info("queryBingdingCard request end!");
			}
		} catch (Exception e) {
			logger.error("queryBingdingCard error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 转换银行列表数据，生成最后手机界面展示
	 * @param list
	 * @return
	 */
	private List<BingdingCardVO> convertCardList(List<BingdingCardVO> list){
		if(list!=null){
			for(BingdingCardVO vo : list){
				//屏蔽银行卡中间的数字
				vo.setBankCard(StringUtil.encryptCardNumberPostFour(vo.getBankCard()));
				vo.setOprPhone(StringUtil.mobileHide4Number(vo.getOprPhone()));
				vo.setDayLimit(limitDesc(Double.parseDouble(vo.getDayLimit())));
				vo.setSingleLimit(limitDesc(Double.parseDouble(vo.getSingleLimit())));
				vo.setCardType(vo.getCardType().equals("01")==true?"储蓄卡":"信用卡");
			}
		}
		return list;
	}

	private String limitDesc(Double single_limit) {
		if( 0 == single_limit ){//TODO syl 能否如此判断 Double 为0 
			return "无限额" ;
		}else{
			return String.valueOf(toWanYuan(BigDecimal.valueOf(single_limit))) ;
		}
	}

	/**
	 * 把传入的数字转换为万级别
	 * @param product_tot_amt
	 * @return
	 */
	private String toWanYuan(BigDecimal product_tot_amt) {
		//modify by wade 2015-10-09 测试中发现 0.99/10000 发生科学计数法所以只能使用BigDecimal来计算了
		//且使用stripTrailingZeros去掉精度后面多余的0，用toPlainString避免科学计数法显示
		//BigDecimal b1 = new BigDecimal(Double.toString(product_tot_amt));
		BigDecimal b2 = new BigDecimal(Double.toString(10000));
		//转为万除以10000,然后再考虑分100所有需要6为小数
		String result = product_tot_amt.divide(b2, 6, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
		result = result + "万";
		return result;
	}
	/**
	 * 修改用户登陆密码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/chgLoginPwd")
	@ResponseBody
	public synchronized ResultMap chgLoginPwd(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		if( logger.isInfoEnabled() ){
			logger.info("chgLoginPwd request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();
			String oldLoginPwd =  request.getParameter("oldLoginPwd");///旧登陆密码
			String loginPwd =  request.getParameter("loginPwd");//新登陆密码

			//检查数据是否为空
			if(BasicUtils.isEmpty(oldLoginPwd, loginPwd) || userId == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			// 1，检查用户是否存在
			UserDTO userInfo = userService.queryUserById(userId);

			//用户存在
			if(userInfo == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
				return result;
			}
			//登陆密码是否匹配
			if(userInfo.getPassword().equals(SecureUtil.MD5EncryptAndBase64(oldLoginPwd))){

				//如果交易密码和新的登陆密码相同
				if( SecureUtil.MD5EncryptAndBase64(loginPwd).equals(userInfo.getTradePwd()) ){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_4006);
					result.setMessage("交易密码和支付密码不能一样");
				}else{
					userInfo.setPassword(SecureUtil.MD5EncryptAndBase64(loginPwd));
					userService.updateUser(userInfo);
					result.setStatus(STATUS.SUCCESS);
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				}
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PWS_ERROR);
				result.setMessage("帐户名密码错误");
			}

			if( logger.isInfoEnabled() ){
				logger.info("chgLoginPwd request end!");
			}

		} catch (Exception e) {
			logger.error("chgLoginPwd error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 用户交易记录
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/transactionLog")
	@ResponseBody
	public synchronized ResultMap transactionLog(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("transactionLog request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();

			// 1，检查用户是否存在
			UserDTO userInfo = userService.queryUserById(userId);

			//用户存在
			if(userInfo == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
			}

			//分页参数  activitieGiftServiceImpl.countActivitiesGift(loginUser.getId())
			int pageNo = 1;
			int pageSize = 10;
			if(StringUtils.isNotBlank(request.getParameter("pageNo"))){
				pageNo = Integer.valueOf(request.getParameter("pageNo"));
			}
			if(StringUtils.isNotBlank(request.getParameter("pageSize"))){
				pageSize = Integer.valueOf(request.getParameter("pageSize"));
			}
			Pager pager = new Pager();
			pager.setPageNo(pageNo);
			pager.setPageSize(pageSize);


			Map<String,String> map = new HashMap<String, String>();
			map.put("userId", userId.toString());
			map.put("startIndex", pager.getStartIndex()+"");
			map.put("pageSize", pager.getPageSize()+"");
			List<FpPaymentDTO> list = paymentServiceImpl.queryPaymentList(map);

			List<PaymentVO> listVO = convertPaymentList(list);
			pager.setTotalCount(paymentServiceImpl.queryPaymentListCount(map));
			result.setAttribute("list", listVO);
			result.setAttribute("pager", pager);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			if( logger.isInfoEnabled() ){
				logger.info("transactionLog request end!");
			}
		} catch (Exception e) {
			logger.error("transactionLog error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 用户交易记录
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/transactionLogDetailed")
	@ResponseBody
	public synchronized ResultMap transactionLogDetailed(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		if( logger.isInfoEnabled() ){
			logger.info("transactionLogDetailed request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();
			String platSerialNo =  request.getParameter("platSerialNo");//新登陆密码

			//检查数据是否为空
			if(BasicUtils.isEmpty(platSerialNo) || userId == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			// 1，检查用户是否存在
			UserDTO userInfo = userService.queryUserById(userId);

			//用户存在
			if(userInfo == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
			}


			//记录平台的支付流水记录
			Map<String,String> map = new HashMap<String, String>();
			map.put("platSerialNo", platSerialNo);
			FpPaymentDTO paymentUp =  paymentServiceImpl.loadByOrderId(map);

			PaymentVO vo = new PaymentVO();
			vo.setPaymentDate(paymentUp.getPayStartTime());
			vo.setPaymentEndDate(paymentUp.getPayEndTime());
			vo.setPayStatus(paymentUp.getPayStatus());
			vo.setPayType(paymentUp.getInterfaceType());
			vo.setPayAmt(paymentUp.getPayAmt());
			vo.setPayMode(new StringBuffer().append(paymentUp.getPayMode()).append("(").append(StringUtil.encryptCardNumberPostFour(paymentUp.getCardNo())).append(")").toString());
			vo.setPlatSerialNo(paymentUp.getPlatSerialNo());
			vo.setProductName(paymentUp.getPayDesc());
			vo.setPayRetMsg(paymentUp.getTpayRetMsg());

			result.setAttribute("bean", vo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			if( logger.isInfoEnabled() ){
				logger.info("transactionLogDetailed request end!");
			}
		} catch (Exception e) {
			logger.error("transactionLogDetailed error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 校验用户的交易密码是否正确，使用场景
	 * 1：解除绑卡
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/checkTradePwd")
	@ResponseBody
	public ResultMap checkTradePwd(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		if( logger.isInfoEnabled() ){
			logger.info("checkTradePwd request begin!");
		}
		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();
			String tradePwd =  request.getParameter("tradePwd");//新登陆密码

			//检查数据是否为空
			if(BasicUtils.isEmpty(tradePwd) || userId == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			// 1，检查用户是否存在
			UserDTO userInfo = userService.queryUserById(userId);

			//用户存在
			if(userInfo == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
			}


			//2,检查交易密码

			String userTradePwd = userInfo.getTradePwd();//交易密码

			//如果用户当前处于手势密码锁定的状态，则不再验证，直接退出
			if(BizEnums.UserEnums.USER_STATUS_TRADE_LOCK.equals(userInfo.getFaStatus())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_USER_STATUS_TRADE_LOCK);
				result.setMessage("用户交易密码锁定");
			}else{
				//原本手势密码不为空，且用户输入的密码和手势密码相同
				if(SecureUtil.MD5EncryptAndBase64(tradePwd).equals(userTradePwd)){
					result.setStatus(STATUS.SUCCESS);
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

					userInfo.setTradeErrTimes(0l);//重置交易密码失败次数为0
					userService.updateUser(userInfo);
				}else{
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_4011);
					result.setMessage("交易密码不正确");

					//获取用户当前的输入错误次数
					long errTimes = userInfo.getTradeErrTimes();//输入的交易密码错误次数
					errTimes = errTimes + 1;//本次错误追加1次

					//当错误次数大于3次时，提示客户还有几次机会会被锁定
					if(errTimes>=BizEnums.UserEnums.USER_ERROR_TRADE_ALERT_LIMIT){
						result.setAttribute("remainingErrorNumber", BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes);
						logger.info( "已错误"+errTimes+"次，还有"+(BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES-errTimes)+"次机会将被锁定！" );
					}

					if(errTimes >= BizEnums.UserEnums.USER_ERROR_TRADE_LIMIT_TIMES){
						//错误次数超限
						logger.warn("user<"+userId+"> trade password lock");
						userInfo.setFaStatus(BizEnums.UserEnums.USER_STATUS_TRADE_LOCK);
					}
					userInfo.setTradeErrTimes(errTimes);
					userService.updateUser(userInfo);
				}
			}
			if( logger.isInfoEnabled() ){
				logger.info("checkTradePwd request end!");
			}
		} catch (Exception e) {
			logger.error("checkTradePwd error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 转换银行列表数据，生成最后手机界面展示
	 * @param list
	 * @return
	 */
	private List<PaymentVO> convertPaymentList(List<FpPaymentDTO> list){
		List<PaymentVO> listVO = new ArrayList<PaymentVO>();
		if(list!=null){
			for(FpPaymentDTO bean : list){
				PaymentVO vo = new PaymentVO();
				vo.setPaymentDate(bean.getPayStartTime());
				vo.setPayStatus(bean.getPayStatus());
				vo.setPayType(bean.getInterfaceType());
				vo.setPayAmt(bean.getPayAmt());
				vo.setPayMode(new StringBuffer().append(bean.getPayMode()).append("(").append(StringUtil.encryptCardNumberPostFour(bean.getCardNo())).append(")").toString());
				vo.setPlatSerialNo(bean.getPlatSerialNo());
				listVO.add(vo);
			}
		}
		return listVO;
	}

	/**
	 * 忘记登陆密码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/forgetLoginPwd")
	@ResponseBody
	public synchronized ResultMap forgetLoginPwd(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		if( logger.isInfoEnabled() ){
			logger.info("forgetLoginPwd request begin!");
		}
		try {

			String loginPwd =  request.getParameter("confirmPassword");//登录密码
			String phone =  request.getParameter("mobile");//新的交易密码
			String smsCode =  request.getParameter("smsCode");//短信验证码

			//校验数据是否有空
			//如果输入参数有一个为空，则中断后返回前端
			if(BasicUtils.isEmpty(phone, smsCode, loginPwd)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			if(!userService.isMobileRegistered(phone)){
				log.info("repeat mobile no");
				//已经被注册
				result.setStatus(ResultMap.STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_MOBILE_NUMBER_UNDEFINED);
				result.setMessage("手机号码未注册！");
				return result;
			}

			//2, 检查短信验证是否通过(只检查验证码是否有效)
			//校验验证码
			if(checkCodeServiceImpl.CheckCodeSwitch()){
				ResultMap resultOtp = checkOtpCode(phone,smsCode);

				if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
					result.setStatus(resultOtp.getStatus());
					result.setStatusCode(resultOtp.getStatusCode());
					result.setMessage(resultOtp.getMessage());
					return result;
				}
			}

			UserDTO userInfo = new UserDTO();
			userInfo.setLoginName(phone);
			userInfo.setPassword(SecureUtil.MD5EncryptAndBase64(loginPwd));
			userService.updateUser(userInfo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			if( logger.isInfoEnabled() ){
				logger.info("forgetLoginPwd request end!");
			}
		} catch (Exception e) {
			logger.error("forgetLoginPwd error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 忘记交易密码
	 * @param model
	 * @param content
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/forgetTradePwd")
	@ResponseBody
	public synchronized ResultMap forgetTradePwd(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();

		if( logger.isInfoEnabled() ){
			logger.info("forgetTradePwd request begin!");
		}

		try {

			Session session = getSession(true);
			UserDTO loginUser = session.getUser();

			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			String userId = loginUser.getId();



			String loginPwd =  request.getParameter("loginPwd");//登录密码
			String tradePwd =  request.getParameter("tradePwd");//新的交易密码
			String smsCode =  request.getParameter("smsCode");//短信验证码


			//检查数据是否为空
			if(BasicUtils.isEmpty(loginPwd, tradePwd,smsCode)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			// 1，检查用户是否存在
			UserDTO userInfo = userService.queryUserById(userId);
			if(userInfo==null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("用户不存在");
				return result;
			}

			//2，检查登陆密码是否匹配
			if(!userInfo.getPassword().equals(SecureUtil.MD5EncryptAndBase64(loginPwd))){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PWS_ERROR);
				result.setMessage("帐户名密码错误");
				return result;
			}

			//3，交易密码不能与登陆密码一样
			if( userInfo.getPassword() .equals(SecureUtil.MD5EncryptAndBase64(tradePwd)) ){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4006);
				result.setMessage("不能与登陆密码一样");
				return result;
			}

			//4，密码长度检查
			if( 6 > tradePwd.length() ||  tradePwd.length() > 20 ){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_TYPE_ERROR);
				result.setMessage("交易密码长度只能6-20位");
				return result;
			}

			//5、检查短信验证是否通过(只检查验证码是否有效)
			if(checkCodeServiceImpl.CheckCodeSwitch()){
				Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
				//验证码超时
				if(checkOtpCodeTimeOut(loginUser.getLoginName(),activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
					result.setStatus(ResultMap.STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
					result.setMessage("手机验证码超时！");
					return result;

				};
				ResultMap resultOtp = checkOtpCode(loginUser.getLoginName(),smsCode);
				if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
					result.setStatus(resultOtp.getStatus());
					result.setStatusCode(resultOtp.getStatusCode());
					result.setMessage(resultOtp.getMessage());
					return result;
				}
			}

			//是否设置交易密码
			if(StringUtils.isNotEmpty(userInfo.getTradePwd())){
				userInfo.setTradePwd(SecureUtil.MD5EncryptAndBase64(tradePwd));

				String userStatus = userInfo.getFaStatus();//用户当前状态
				//如果用户是交易密码锁定状态，那么重置为有效，避免恶意用户使用该功能更改自身状态非法操作
				if(BizEnums.UserEnums.USER_STATUS_TRADE_LOCK.equals(userStatus)){
					userInfo.setFaStatus(BizEnums.UserEnums.USER_STATUS_NORMAL);//有效状态
				}

				userInfo.setTradeErrTimes(0l);//有可能用户多次尝试交易密码
				userService.updateUser(userInfo);

				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			}else{
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_4008);
				result.setMessage("支付-交易密码不存在");
			}
			if( logger.isInfoEnabled() ){
				logger.info("forgetTradePwd request e!");
			}

		} catch (Exception e) {

			logger.error("forgetTradePwd error:", e);
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);

		}
		return result;
	}


	/**
	 * 根据手机号 获取用户信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getUserForLonginName")
	@ResponseBody
	public ResultMap getUserForLonginName(HttpServletRequest request, HttpServletResponse response,String loginName){

		ResultMap result = new ResultMap();
		try {
			log.info("In  getUserForLonginName Begin!");

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			//初始化查询参数
			UserDTO query = new UserDTO();
			query.setLoginName(loginName);
			query = userService.queryUserByMobile(query);

			result.setAttribute("dto", query);

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			log.info("In  getUserForLonginName end!");
		}catch(Exception e) {
			logger.error("get getUserForLonginName error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 根据手机号 获取用户说说
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getUserSaySayForLonginName")
	@ResponseBody
	public ResultMap getUserSaySayForLonginName(HttpServletRequest request, HttpServletResponse response,String loginName,FpFaUserSaysayDTO fpFaUserSaysay,Pager pager){

		ResultMap result = new ResultMap();
		try {
			log.info("In  getUserSaySayForLonginName Begin!");

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			//初始化查询参数
			UserDTO query = new UserDTO();
			query.setLoginName(loginName);
			query = userService.queryUserLoginName(query);


			fpFaUserSaysay.setUserId(query.getId());
			fpFaUserSaysay.setBegin(pager.getStartIndex());
			fpFaUserSaysay.setPageSize(pager.getPageSize());

			fpFaUserSaysay.setDeleteTag("1");

			int count = fpFaUserSaysayService.queryListCount(fpFaUserSaysay);

			pager.setTotalCount(count);

			List<FpFaUserSaysayDTO> fpFaUserSaysayList = null;

			if(count > 0){
				fpFaUserSaysayList = fpFaUserSaysayService.queryList(fpFaUserSaysay);
			}else{
				fpFaUserSaysayList = Collections.emptyList();
			}

			result.setAttribute("pager", pager);
			result.setAttribute("list", fpFaUserSaysayList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			log.info("In  getUserSaySayForLonginName end!");
		}catch(Exception e) {
			logger.error("get getUserSaySayForLonginName error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 根据手机号 获取用户信息  v2
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("forLonginNameGetUser")
	@ResponseBody
	public ResultMap forLonginNameGetUser(HttpServletRequest request, HttpServletResponse response,String loginName){

		ResultMap result = new ResultMap();
		try {
			log.info("In  forLonginNameGetUser Begin!");

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				logger.error("get forLonginNameGetUser loginName is null",null);
				UserDTO user = SessionUtil.getSession().getUser();
				String phone=user.getLoginName();
				loginName = phone;
			}

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			//初始化查询参数
			UserDTO query = new UserDTO();
			query.setLoginName(loginName);
			query = userService.queryUserByMobile(query);

			if(query  == null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_TYPE_ERROR);
				result.setMessage("参数缺失");
				return result;
			}
			result.setAttribute("dto", query);


			//查询资讯关联

			FpShopProjectInformationDTO spi = new FpShopProjectInformationDTO();
			spi.setULoginName(loginName);
			//			String informationId = request.getParameter("informationId");
			//			if(StringUtils.isBlank(informationId)){
			//				informationId="0";
			//			}		
			//			spi.setInformationId(Integer.valueOf(informationId));

			List<FpShopProjectInformationDTO> spis = fpShopProjectInformationService.queryList(spi);
			if(spis.size()>0){
				result.setAttribute("pro", spis.get(0));
			}

			String wechatId = (String) SessionUtil.getSession(true).getAttribute(WeixinController.OPENID);
			if(StringUtils.isNotBlank(wechatId)){
				result.setAttribute("wechatId", wechatId);
			}

			String productId=request.getParameter("productId");
			String productType=request.getParameter("productType");
			if(!StringUtil.isNullOrEmptyNStr(productId,productType)){
				FpShopperProductDTO shop=new FpShopperProductDTO();
				shop.setProductId(productId);
				shop.setProductType(productType);
				shop.setUserId(query.getId());
				FpShopperProductDTO shopperProductDto = fpShopperProductService.queryListGetFirst(shop);
				result.setAttribute("shopperProductDto", shopperProductDto);
			}

			//查询店主个人信息
			try {
				ShopperUserInfoDTO shopperUserInfo=new ShopperUserInfoDTO();
				//用户id
				shopperUserInfo.setUserId(query.getId());
				ShopperUserInfoDTO shopperUserInfoDto = shopperUserInfoService.queryListGetFirst(shopperUserInfo);
				result.setAttribute("shopperUserInfoDto",shopperUserInfoDto);

				//查询英雄帖开关信息
				SwitchDTO shopYxtFunction = isystemService.getSwitch("shopYxtFunction");
				SwitchDTO shopYxtAd = isystemService.getSwitch("shopYxtAd");

				result.setAttribute("shopYxtFunction",shopYxtFunction.getValue());
				result.setAttribute("shopYxtAd",shopYxtAd.getValue());

			} catch (Exception e) {
				//e.printStackTrace();
				//System.out.println(e);
				logger.error("get ShopperUserInfoDTO error",e);
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			log.info("In  forLonginNameGetUser end!");
		}catch(Exception e) {
			e.printStackTrace();
			logger.error("get forLonginNameGetUser error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 根据手机号 获取用户说说  v2
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("forLonginNameGetUserSaySay")
	@ResponseBody
	public ResultMap forLonginNameGetUserSaySay(HttpServletRequest request, HttpServletResponse response,String loginName,FpFaUserSaysayDTO fpFaUserSaysay,Pager pager){

		ResultMap result = new ResultMap();
		try {
			log.info("In  forLonginNameGetUserSaySay Begin!");

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				logger.error("get forLonginNameGetUserSaySay loginName is null",null);
				UserDTO user = SessionUtil.getSession().getUser();
				String phone=user.getLoginName();
				loginName = phone;
			}

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			//初始化查询参数
			UserDTO query = new UserDTO();
			query.setLoginName(loginName);
			query = userService.queryUserLoginName(query);
			if(query  == null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_TYPE_ERROR);
				result.setMessage("参数缺失");
				return result;
			}

			fpFaUserSaysay.setUserId(query.getId());
			fpFaUserSaysay.setBegin(pager.getStartIndex());
			fpFaUserSaysay.setPageSize(pager.getPageSize());

			fpFaUserSaysay.setDeleteTag("1");

			int count = fpFaUserSaysayService.queryListCount(fpFaUserSaysay);

			pager.setTotalCount(count);

			List<FpFaUserSaysayDTO> fpFaUserSaysayList = null;

			if(count > 0){
				fpFaUserSaysayList = fpFaUserSaysayService.queryList(fpFaUserSaysay);
				for (FpFaUserSaysayDTO saysayDto:fpFaUserSaysayList) {
					FpFaUserSaysayCommentDTO fpFaUserSaysayComment=new FpFaUserSaysayCommentDTO();
					fpFaUserSaysayComment.setSaysayId(saysayDto.getId());
					fpFaUserSaysayComment.setDeleteTag(CommonEnums.DELETE_FLAG_1);
					List<FpFaUserSaysayCommentDTO> fpFaUserSaysayCommentList = fpFaUserSaysayCommentService.queryList(fpFaUserSaysayComment);
					for (FpFaUserSaysayCommentDTO saysayCommentDto:fpFaUserSaysayCommentList) {
						String commentUserId = saysayCommentDto.getCommentUserId();
						if(StringUtils.isNotBlank(commentUserId)){
							UserDTO u = userService.queryUserById(commentUserId);
							saysayCommentDto.setUserName(u.getUserName());
							saysayCommentDto.setUserHeadImg(u.getuImage());
						}else{
							saysayCommentDto.setUserName("游客");
							try{//去第一张默认头像
								String[] filesName = PropertiesUtils.getValue("faUserImageFile").split(";");
								saysayCommentDto.setUserHeadImg(PropertiesUtils.getValue("faUserImagePath")+filesName[0]);
							}catch(Exception e){
								Log.warn("create fa user image error",e);
							}
						}
					}
					saysayDto.setSaysayCommentList(fpFaUserSaysayCommentList);
				}
			}else{
				fpFaUserSaysayList = Collections.emptyList();
			}

			result.setAttribute("pager", pager);
			result.setAttribute("list", fpFaUserSaysayList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			log.info("In  forLonginNameGetUserSaySay end!");
		}catch(Exception e) {
			logger.error("get forLonginNameGetUserSaySay error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 根据手机号 获取用户说说  v2
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("forLonginNameGetUserProduct")
	@ResponseBody
	public ResultMap forLonginNameGetUserProduct(HttpServletRequest request, HttpServletResponse response, String loginName, FpShopperProductDTO shop, Pager pager){

		ResultMap result = new ResultMap();
		try {
			log.info("In  forLonginNameGetUserProduct Begin!");

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				logger.error("get forLonginNameGetUserProduct loginName is null",null);
				UserDTO user = SessionUtil.getSession().getUser();
				String phone=user.getLoginName();
				loginName = phone;
			}

			//参数为空判断
			if(StringUtils.isBlank(loginName) ){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			//初始化查询参数
			UserDTO query = new UserDTO();
			query.setLoginName(loginName);
			query = userService.queryUserLoginName(query);

			if(query  == null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_TYPE_ERROR);
				result.setMessage("参数缺失");
				return result;
			}

			//用户ID
			shop.setUserId(query.getId());
			shop.setBegin(pager.getStartIndex());
			shop.setPageSize(pager.getPageSize());

			shop.setDeleteTag("1");

			int count = fpShopperProductService.queryShopperProductCount(shop);

			pager.setTotalCount(count);

			List<ShopperProductVO>  list = null;

			if(count > 0){
				//所有产品访问记录
				Map<String, String> productVistCount = getProductVistCount(query.getLoginName());

				list = fpShopperProductService.queryShopperProduct(shop,productVistCount);

			}else{
				list = Collections.emptyList();
			}

			result.setAttribute("pager", pager);
			result.setAttribute("list", list);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			log.info("In  forLonginNameGetUserProduct end!");
		}catch(Exception e) {
			logger.error("get forLonginNameGetUserProduct error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/***
	 * 查询该用户下每个产品的访问记录count
	 * @param loginName
	 * @return
	 */
	public Map<String,String> getProductVistCount(String loginName) {
		String url = mongodbUrl+shopProductRecord;
		url = MessageFormat.format(url,loginName,500,1,"2014-10-10");
		logger.info("goto url: "+url);
		String res = HttpClientUtil.getInstance().doGetRequest(url);
		JSONObject jsonObj = JSONObject.fromObject(res);
		//添加产品销售状态
		JSONObject attributes = jsonObj.getJSONObject("attributes");
		Object o = attributes.get("list");
		JSONArray l = null;
		if(o instanceof JSONObject && ((JSONObject) o).isNullObject()){
			l = new JSONArray();
		}else{
			l = attributes.getJSONArray("list");
		}
		Map<String,String> h=new HashMap<String, String>();
		for (Object object : l) {
			JSONObject j = (JSONObject)object;
			Object type = j.get("type");
			String pId=j.getString("param");
			String c=j.getString("count");
			if(type==null||StringUtils.isBlank(pId)||!(pId+"").matches("[0-9\\-a-zA-Z]+"))
				continue;
			h.put(pId,c);
		}
		return h;
	}

	/**
	 * 根据用户获取组织树
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getOrgTreeByPhone")
	@ResponseBody
	public ResultMap getOrgTreeByPhone(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		try {
			log.info("In  getOrgTreeByPhone Begin!");
			String uPhone = request.getParameter("uPhone");

			//参数为空判断
			if(StringUtils.isBlank(uPhone) ){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			//当前登录用户
			UserDTO currentLogin = SessionUtil.getSession().getUser();

			//查询当前用户是否是理财师
			UserInfoDTO userInfo =  new UserInfoDTO();
			userInfo.setTelePhone(uPhone);
			userInfo.setDeptflag(BizEnums.DeptType.PERSON);//人员
			userInfo.setStatus(0);
//			userInfo.setLayerPath("3ea3a04e-4f70-11e8-b8ea-ecf4bbce3884");//只查销售部
			UserInfoDTO user = userInfoServiceImpl.queryUserInfo(userInfo);//当前登录APP的理财师
			List<ZtreeDto> ztreeDTOList =  new ArrayList<ZtreeDto>();
			if(user==null) {
				UserDTO loginuser = new UserDTO();
				loginuser.setLoginName(uPhone);
				UserDTO u = userService.queryUserLoginName(loginuser);

				ZtreeDto ztdc = new ZtreeDto();
				ztdc = new ZtreeDto();
				ztdc.setId("-1");
				ztdc.setpId("");
				String name = u.getuRealName();
				if(StringUtils.isBlank(u.getuRealName())) {
					name = u.getUserName();
					if(StringUtils.isBlank(u.getUserName())) {
						name = u.getLoginName();
					}
				}
				//是当前登录
				if(currentLogin.getLoginName().equals(u.getLoginName())){
					ztdc.setCurrentLogin(true);
				}
				
				ztdc.setName(name);
				ztreeDTOList.add(ztdc);
			} else {
				//查询当前用户负责的部门
				userInfo =  new UserInfoDTO();
				userInfo.setDeptHead(user.getUserId());
				userInfo.setDeptflag(BizEnums.DeptType.DEPT);//部门
				userInfo.setStatus(0);
				userInfo.setLayerPath("3ea3a04e-4f70-11e8-b8ea-ecf4bbce3884");//只查销售部
				List<UserInfoDTO> deptlist = userInfoServiceImpl.queryAllUserInfo(userInfo);
				if(deptlist.size()>0) {
					String sql = "";//查询条件
					String firstNode = null;//根节点
					int sameLevelNodeNUm=1;//同级节点数
					int i=0;
					if(deptlist.size()==1) {
						sql = " AND layerPath like '%"+deptlist.get(0).getParentUserId()+","+deptlist.get(0).getUserId()+"%'";
						firstNode = deptlist.get(0).getLayerPath();
					} else {
						for(UserInfoDTO u:deptlist) {
							if(i==0) {
								sql += " AND (layerPath like '%"+u.getParentUserId()+","+u.getUserId()+"%'";
							} else if(i==deptlist.size()-1){
								sql += " OR layerPath like '%"+u.getParentUserId()+","+u.getUserId()+"%')";
							} else {
								sql += " OR layerPath like '%"+u.getParentUserId()+","+u.getUserId()+"%'";
							}

							if(firstNode == null) {
								firstNode = u.getLayerPath();
							} else {
								if(firstNode.length() > u.getLayerPath().length()) {
									sameLevelNodeNUm=1;//重置同级节点数
									firstNode = u.getLayerPath();
								} else if(firstNode.length() == u.getLayerPath().length()){//同级节点数
									sameLevelNodeNUm++;
								}
							}

							i++;
						}
					}

					ZtreeDto ztdc = new ZtreeDto();
					if(sameLevelNodeNUm > 1) {
						//最上级菜单同级节点有多个，获取firstNode的上级节点作为根节点
						String[] nodeArr = firstNode.split(",");
						String rootNodeUserId = nodeArr[nodeArr.length-1];
						if(nodeArr.length>1) {
							rootNodeUserId = nodeArr[nodeArr.length-2];
						}
						userInfo =  new UserInfoDTO();
						userInfo.setUserId(rootNodeUserId);
						userInfo.setDeptflag(BizEnums.DeptType.DEPT);
						userInfo.setStatus(0);
						userInfo.setLayerPath("3ea3a04e-4f70-11e8-b8ea-ecf4bbce3884");//只查销售部
						UserInfoDTO rootNodeUser = userInfoServiceImpl.queryUserInfo(userInfo);//当前登录APP的理财师

						//保存根节点
						ztdc.setId(rootNodeUser.getUserId());
						ztdc.setpId("");
						ztdc.setName(rootNodeUser.getUserNickname());
						ztdc.setType(rootNodeUser.getUserType());
						
						//当前登录用户
						if(rootNodeUser.getTelePhone().equals(currentLogin.getLoginName())){
							ztdc.setCurrentLogin(true);
						}
						
						ztreeDTOList.add(ztdc);
					}

					WhereCondition wc = WC.one();
					wc.andCustom(sql);
					List<UserInfoDTO> zTreeData = userInfoServiceImpl.queryOrgTree(wc);

					for(UserInfoDTO ut:zTreeData) {
						ztdc = new ZtreeDto();
						ztdc.setId(ut.getUserId());
						ztdc.setpId(ut.getParentUserId());
						ztdc.setName(ut.getUserNickname());
						ztdc.setType(ut.getUserType());
						//当前登录用户
						if(ut.getTelePhone().equals(currentLogin.getLoginName())){
							ztdc.setCurrentLogin(true);
						}
						ztreeDTOList.add(ztdc);
					}

				} else {
					ZtreeDto ztdc = new ZtreeDto();
					ztdc.setId(user.getUserId());
					ztdc.setpId(user.getParentUserId());
					ztdc.setName(user.getUserNickname());
					ztdc.setType(user.getUserType());
					//当前登录用户
					if(user.getTelePhone().equals(currentLogin.getLoginName())){
						ztdc.setCurrentLogin(true);
					}
					ztreeDTOList.add(ztdc);
				}

				
			}
			result.setAttribute("list", ztreeDTOList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			log.info("In  getOrgTreeByPhone end!");
		}catch(Exception e) {
			logger.error("get getOrgTreeByPhone error",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	public static void main(String[] args) {
		String a = "3f477ef2-e091-11e7-8ce9-0b6cfcab62eb";
		System.out.println(a.length());
	}
}